<template>
    <div class="item_detail">
        <van-swipe :autoplay="3000">
            <van-swipe-item v-for="(image, index) in goods.info.gallery" :key="index">
                <img v-lazy="image" width="100%"/>
            </van-swipe-item>
        </van-swipe>
        <van-cell-group class="item_cell_group" v-if="goods">
            <van-cell class="item_info">
                <div>
                    <span class="item_price">{{ goods.info.price }}</span>
                    <span class="item_market_price">{{goods.info.price}}</span>
                </div>
                <div class="item-title">{{ goods.info.name }}</div>
                <div class="item_intro">{{goods.info.brief}}</div>
            </van-cell>
        </van-cell-group>

        <div class="item_cell_group">
            <!--      <van-cell-group>
                    <van-cell title="规格" isLink value="请选择" @click.native="skuClick" />
                    &lt;!&ndash; <van-cell title="属性" isLink @click.native="propsPopup = true" /> &ndash;&gt;
                    &lt;!&ndash; <van-cell title="运费" value="满88免邮费" /> &ndash;&gt;
                  </van-cell-group>-->
            <!-- <van-sku
              v-model="showSku"
              :sku="sku"
              :hide-stock="true"
              :goods="skuGoods"
              :goodsId="goods.info.id"
              @buy-clicked="buyGoods"
              @add-cart="addCart"
            />
            -->
            <van-sku
                    v-model="showSku"
                    :sku="sku"
                    :goods="skuGoods"
                    :goods-id="goodsId"
                    :quota="quota"
                    :quota-used="quotaUsed"
                    :hide-stock="sku.hide_stock"
                    :message-config="messageConfig"
                    @buy-clicked="buyGoods"
                    @add-cart="addCart"
                    :close-on-click-overlay="true"
            />
        </div>
        <div class="item_desc">
            <div class="item_desc_title">商品详情</div>
            <div class="item_desc_wrap" v-if="goods.info.detail" v-html="goods.info.detail"></div>
            <div class="item_desc_wrap" v-else style="text-align: center;">
                <p>无详情</p>
            </div>
        </div>

        <van-goods-action>
            <van-goods-action-button type="warning" @click="skuClick" text="加入购物车"/>
            <van-goods-action-button type="danger" @click="skuClick" text="立即购买"/>
        </van-goods-action>
    </div>
</template>

<script>
    import {
        goodsDetail,
        cartGoodsCount,
        collectAddOrDelete,
        cartAdd,
        cartFastAdd,
        wxShareConfig
    } from '@/api/api';

    import {
        Sku,
        Swipe,
        SwipeItem,
        GoodsAction,
        GoodsActionButton,
        GoodsActionIcon,
        Popup,
        Grid,
        Toast,
        GridItem,
    } from 'vant';
    import {setLocalStorage} from '@/utils/local-storage';
    import popupProps from './popup-props';
    import _ from 'lodash';
    import wx from 'weixin-js-sdk'

    export default {
        props: {
            itemId: [String, Number]
        },

        data() {
            const isLogin = !!localStorage.getItem('Authorization');

            return {
                isLogin,
                shareConfig:{},
                goodsbrief: [
                    {
                        title: '品名',
                        intro: '新鲜牦牛肉'
                    },
                    {
                        title: '储藏方式',
                        intro: '冷藏'
                    },
                    {
                        title: '净含量',
                        intro: '500g'
                    }
                ],
                goodsId: '',
                goods: {
                    info: {
                        gallery: [],
                        retailPrice: 100,
                        counterPrice: 80
                    },
                    name: 'name',
                    brief: 'brief'
                },
                // 购物车配置Start
                sku: {
                    // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
                    // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
                    tree: [],
                    // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
                    list: [],
                    price: '1.00', // 默认价格（单位元）
                    stock_num: 227, // 商品总库存
                    collection_id: 2259, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
                    none_sku: false, // 是否无规格商品
                    hide_stock: false // 是否隐藏剩余库存
                },
                messageConfig: {},
                skuGoods: {
                    // 商品标题
                    title: '测试商品',
                    // 默认商品 sku 缩略图
                    picture: 'https://img.yzcdn.cn/1.jpg'
                },
                quota: 0, // 限购买数  0--不限购
                quotaUsed: 0, // 已购买数
                // 购物车配置end
                cartInfo: 0,
                selectSku: {
                    selectedNum: 1,
                    selectedSkuComb: {
                        sku_str: 'aa'
                    }
                },
                propsPopup: false,
                showSku: false
            };
        },

        computed: {
            props_str() {
                let props_arr = [];
                _.each(this.goods.attribute, json => {
                    props_arr.push([json['attribute'], json['value']]);
                });
                return props_arr || [];
            }
        },
        activated() {
            this.initData();
            // this.initShare();
        },
        methods: {
            initShare(){
                var This=this;
                var currentUrl=window.location.href;
                wxShareConfig({url: currentUrl}).then(res => {
                    var config = res.data.result;
                    This.shareConfig=config;
                    wx.config({
                        beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来
                        appId: config.appId, // 必填，企业微信的corpID
                        timestamp: config.timestamp, // 必填，生成签名的时间戳
                        nonceStr: config.nonceStr, // 必填，生成签名的随机串 必填，生成签名的随机串
                        signature: config.signature, // 必填，签名
                        jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline']
                    });
                    wx.ready(function(){
                        wx.onMenuShareAppMessage({
                            title: '万货全商城-绿色商城', // 分享标题
                            desc: This.goods.info.name, // 分享描述
                            link: This.shareConfig.shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: 'http://www.spwhq.com/upload/p/p1.jpg', // 分享图标(不能赋相对路径，一定要是绝对路径)
                            success: () => {
                            }
                        });
                        wx.onMenuShareTimeline({
                            title: '万货全商城-绿色商城', // 分享标题
                            desc: This.goods.info.name, // 分享描述
                            link: This.shareConfig.shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: 'http://www.spwhq.com/upload/p/p1.jpg', // 分享图标(不能赋相对路径，一定要是绝对路径)
                            success: () => {
                            }
                        });
                    });
                });

            },
            skuClick() {
                this.showSku = true;
            },
            initData() {
                var This = this;
                let productId = this.$route.params.id;
                this.goodsId = productId;
                goodsDetail({id: productId}).then(res => {
                    let data = res.data.result;
                    This.goods.info.gallery = data.pic.split(",");
                    This.goods.info.price = data.price;
                    This.goods.info.name = data.name;
                    This.goods.info.brief = data.subTitle;
                    This.goods.info.detail = data.description;

                    This.goodsId = data.id;
                    This.goodsPrice = data.price;
                    This.skuGoods.title = data.name;
                    This.skuGoods.picture = data.headPic;
                    This.sku.price = data.price;
                    This.sku.stock_num = 9999;
                    This.initShare();
                });
            },
            toCart() {
                this.$router.push({
                    name: 'cart'
                });
            },
            getProductId(s1, s2) {
                var productId;
                var s1_name;
                var s2_name;
                _.each(this.goods.specificationList, specification => {
                    _.each(specification.valueList, specValue => {
                        if (specValue.id === s1) {
                            s1_name = specValue.value;
                        } else if (specValue.id === s2) {
                            s2_name = specValue.value;
                        }
                    });
                });

                _.each(this.goods.productList, v => {
                    let result = _.without(v.specifications, s1_name, s2_name);
                    if (result.length === 0) {
                        productId = v.id;
                    }
                });
                return productId;
            },
            getProductIdByOne(s1) {
                var productId;
                var s1_name;
                _.each(this.goods.specificationList, specification => {
                    _.each(specification.valueList, specValue => {
                        if (specValue.id === s1) {
                            s1_name = specValue.value;
                            return;
                        }
                    });
                });

                _.each(this.goods.productList, v => {
                    let result = _.without(v.specifications, s1_name);
                    if (result.length === 0) {
                        productId = v.id;
                    }
                });
                return productId;
            },
            addCart(skuData) {
                var This = this;
                const addCar = {};
                addCar.productId = this.goodsId;
                addCar.quantity = skuData.selectedNum;
                addCar.addPrice = this.goodsPrice;
                cartAdd(addCar).then(res => {
                    Toast.success('添加成功');
                    This.showSku=false;
                });
            },
            buyGoods(skuData) {
                setLocalStorage({submitProductIds:skuData.goodsId,submitQuantity:skuData.selectedNum});
                this.$router.push('/order/checkout');
            }
        },

        components: {
            [Toast.name]: Toast,
            [Popup.name]: Popup,
            [Swipe.name]: Swipe,
            [SwipeItem.name]: SwipeItem,
            [Sku.name]: Sku,
            [GoodsAction.name]: GoodsAction,
            [GoodsActionButton.name]: GoodsActionButton,
            [GoodsActionIcon.name]: GoodsActionIcon,
            [popupProps.name]: popupProps,
            [Grid.name]: Grid,
            [GridItem.name]: GridItem
        }
    };
</script>

<style lang="scss" scoped>
    .item_detail {
        img {
            max-width: 100%;
        }
    }

    .item_cell_group {
        margin-bottom: 15px;
    }

    .item_price {
        font-size: 20px;
        color: $red;
        margin-right: 10px;
    }

    .item_market_price {
        color: $font-color-gray;
        text-decoration: line-through;
        font-size: $font-size-small;
    }

    .item-title {
        line-height: 1.4;
    }

    .item_dispatch {
        font-size: $font-size-small;
        color: $font-color-gray;
    }

    .item_intro {
        line-height: 18px;
        margin: 5px 0;
        font-size: $font-size-small;
        color: $font-color-gray;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
    }

    .item_desc {
        background-color: #fff;

        /deep/ p {
            padding: 0 10px;
            margin-block-start: 0 !important;
            margin-block-end: 0 !important;
        }

        /deep/ img {
            max-width: 100%;
            display: block;
        }
    }

    .item_desc_title {
        @include one-border;
        padding: 10px 0;
        text-align: center;
    }
</style>
